import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/features/finance/models/monthly_bill_model.dart';
import 'package:family_app/src/features/finance/models/transaction_model.dart';
import 'package:family_app/src/features/finance/providers/finance_provider.dart';
import 'package:family_app/src/features/finance/screens/bill_detail_screen.dart';
import 'package:family_app/src/features/finance/widgets/transaction_list_item.dart';
import 'package:family_app/src/features/auth/providers/auth_provider.dart';
import 'package:family_app/src/theme/app_theme.dart';

// 自定义卡片阴影
final _cardShadow = [
  BoxShadow(
    color: Colors.black.withOpacity(0.05),
    blurRadius: 10,
    offset: const Offset(0, 4),
  ),
];

/// 月份统计条目组件
/// 显示月份的收入、支出、结余统计，点击可展开显示该月交易明细
class MonthSummaryTile extends ConsumerStatefulWidget {
  final int year;
  final int month;
  final MonthlyBillModel? bill; // 新增bill参数

  const MonthSummaryTile({
    Key? key,
    required this.year,
    required this.month,
    this.bill,
  }) : super(key: key);

  @override
  ConsumerState<MonthSummaryTile> createState() => _MonthSummaryTileState();
}

class _MonthSummaryTileState extends ConsumerState<MonthSummaryTile> {
  bool _isExpanded = false; // 展开状态

  @override
  Widget build(BuildContext context) {
    // 创建月份的第一天和最后一天，用于查询该月交易
    final firstDayOfMonth = DateTime(widget.year, widget.month, 1);
    final lastDayOfMonth = DateTime(widget.year, widget.month + 1, 0);
    final dateRange = (firstDayOfMonth, lastDayOfMonth);
    final theme = Theme.of(context);

    // 只有在展开状态时才获取该月的交易数据
    final monthTransactionsAsync = _isExpanded 
        ? ref.watch(monthTransactionsProvider(dateRange))
        : const AsyncValue<List<TransactionModel>>.loading();

    // 从bill对象中获取收入和支出（如果有），否则从provider中获取
    // 如果widget.bill存在，直接使用其中的数据，不再从provider获取
    final monthIncomeAsync = widget.bill != null
        ? AsyncValue.data(widget.bill!.totalIncomeMoney)
        : ref.watch(monthIncomeProvider(dateRange));
    final monthExpenseAsync = widget.bill != null
        ? AsyncValue.data(widget.bill!.totalExpenseMoney)
        : ref.watch(monthExpenseProvider(dateRange));
    final monthBalanceAsync = widget.bill != null
        ? AsyncValue.data(widget.bill!.totalIncomeMoney - widget.bill!.totalExpenseMoney)
        : ref.watch(monthBalanceProvider(dateRange));

    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 6.h),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        color: theme.cardColor,
        boxShadow: _cardShadow,
      ),
      child: Theme(
        data: theme.copyWith(dividerColor: Colors.transparent),
        child: Column(
          children: [
            // 月份摘要行（点击展开/收起）
            Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: () {
                  // 切换展开状态
                  setState(() {
                    _isExpanded = !_isExpanded;
                  });
                },
                borderRadius: _isExpanded 
                    ? BorderRadius.only(
                        topLeft: Radius.circular(12.r),
                        topRight: Radius.circular(12.r),
                      )
                    : BorderRadius.circular(12.r),
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      // 月份标题
                      Container(
                        width: 48.w,
                        height: 48.w,
                        decoration: BoxDecoration(
                          color: theme.primaryColor.withOpacity(0.1),
                          shape: BoxShape.circle,
                        ),
                        child: Center(
                          child: Text(
                            '${widget.month}月',
                            style: TextStyle(
                              fontSize: 15.sp,
                              fontWeight: FontWeight.w600,
                              color: theme.primaryColor,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(width: 12.w),
                      // 收入
                      Expanded(
                        child: _buildSummaryItem(
                          context,
                          '收入',
                          monthIncomeAsync,
                          Colors.green,
                        ),
                      ),
                      // 分隔线
                      Container(
                        width: 1,
                        height: 24.h,
                        margin: EdgeInsets.symmetric(horizontal: 8.w),
                        color: theme.dividerColor.withOpacity(0.3),
                      ),
                      // 支出
                      Expanded(
                        child: _buildSummaryItem(
                          context,
                          '支出',
                          monthExpenseAsync,
                          Colors.red,
                        ),
                      ),
                      // 展开/收起图标
                      AnimatedRotation(
                        duration: const Duration(milliseconds: 300),
                        turns: _isExpanded ? 0.5 : 0,
                        child: Icon(
                          Icons.keyboard_arrow_down,
                          color: theme.hintColor,
                          size: 24.sp,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            // 展开的交易列表
            AnimatedContainer(
              duration: const Duration(milliseconds: 300),
              height: _isExpanded ? null : 0,
              child: _isExpanded ? _buildTransactionList(monthTransactionsAsync) : null,
            ),
          ],
        ),
      ),
    );
  }

  // 构建摘要项
  Widget _buildSummaryItem(
    BuildContext context,
    String label,
    AsyncValue<int> value,
    Color color, {
    bool hasError = false,
  }) {
    final textTheme = Theme.of(context).textTheme;
    
    return value.when(
      data: (amount) => Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            label,
            style: textTheme.bodySmall?.copyWith(
              color: Theme.of(context).hintColor,
              fontSize: 12.sp,
            ),
          ),
          SizedBox(height: 2.h),
          Text(
            '¥${amount.toStringAsFixed(2)}',
            style: textTheme.titleSmall?.copyWith(
              color: hasError ? Colors.red : color,
              fontWeight: FontWeight.w600,
              fontSize: 14.sp,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
      loading: () => const Center(
        child: SizedBox(
          width: 20,
          height: 20,
          child: CircularProgressIndicator(strokeWidth: 2),
        ),
      ),
      error: (_, __) => _buildSummaryItem(
        context,
        label,
        const AsyncValue.data(0),
        color,
        hasError: true,
      ),
    );
  }



  // 构建展开的交易列表
  Widget _buildTransactionList(AsyncValue<List<TransactionModel>> transactionsAsync) {
    return transactionsAsync.when(
      data: (transactions) {
        if (transactions.isEmpty) {
          return Container(
            padding: EdgeInsets.all(24.w),
            child: Column(
              children: [
                Icon(
                  Icons.receipt_long_outlined,
                  size: 48.sp,
                  color: Theme.of(context).hintColor.withOpacity(0.5),
                ),
                SizedBox(height: 8.h),
                Text(
                  '本月暂无交易记录',
                  style: TextStyle(
                    color: Theme.of(context).hintColor,
                    fontSize: 14.sp,
                  ),
                ),
              ],
            ),
          );
        }

        // 按日期排序交易（最新的在前）
        final sortedTransactions = List<TransactionModel>.from(transactions)
          ..sort((a, b) => b.transactionDate.compareTo(a.transactionDate));

        return Container(
          decoration: BoxDecoration(
            border: Border(
              top: BorderSide(
                color: Theme.of(context).dividerColor.withOpacity(0.3),
                width: 1,
              ),
            ),
          ),
          child: ListView.separated(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            padding: EdgeInsets.symmetric(vertical: 8.h),
            itemCount: sortedTransactions.length,
            separatorBuilder: (context, index) => Divider(
              height: 1,
              color: Theme.of(context).dividerColor.withOpacity(0.1),
            ),
            itemBuilder: (context, index) {
              final transaction = sortedTransactions[index];
              return TransactionListItem(
                transaction: transaction,
                onTap: () {
                  // 可以在这里添加点击交易项的处理逻辑
                },
                onDelete: () {
                  // 可以在这里添加删除交易项的处理逻辑
                },
              );
            },
          ),
        );
      },
      loading: () => Container(
        padding: EdgeInsets.all(24.w),
        child: const Center(
          child: CircularProgressIndicator(),
        ),
      ),
      error: (error, stackTrace) => Container(
        padding: EdgeInsets.all(24.w),
        child: Column(
          children: [
            Icon(
              Icons.error_outline,
              size: 48.sp,
              color: Colors.red.withOpacity(0.5),
            ),
            SizedBox(height: 8.h),
            Text(
              '加载交易记录失败',
              style: TextStyle(
                color: Colors.red,
                fontSize: 14.sp,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _navigateToBillDetail(BuildContext context) {
    // 获取当前用户ID
    final authState = ref.read(authStateProvider);
    if (authState.user == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请先登录')),
      );
      return;
    }

    // 导航到详细账单页面
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => BillDetailScreen(
          userId: int.tryParse(authState.user!.id) ?? 0,
          type: 0, // 0表示全部类型
          secondClassifyId: 0, // 0表示全部分类
          date: '${widget.year}-${widget.month.toString().padLeft(2, '0')}',
          title: '${widget.year}年${widget.month}月账单详情',
        ),
      ),
    );
  }
}
